#include "rb_tree.h"

namespace mian_yang
{
    template <class K, class V>
    class map
    {
        struct KeyOfT
        {
            K operator()(const pair<const K, V> &kv)
            {
                return kv.first;
            }
        };

    public:
        typedef RBTree<K, pair<const K, V>, KeyOfT> rb_tree;
        typedef typename RBTree<K, pair<const K, V>, KeyOfT>::Iterator Iterator;
        typedef typename RBTree<K, pair<const K, V>, KeyOfT>::const_Iterator const_Iterator;

    public:
        pair<Iterator, bool> insert(const pair<const K, V> &kv) /*这里要加const， 为什么， 因为c++的类型检查很严格， 非const 引用不能引用常量*/
        {
            return rb.Insert(kv);
        }

        V& operator[](const K &key)
        {
            pair<Iterator, bool> ret = insert(make_pair(key, V()));
            return (ret.first)->second;
        }

        void InOrder()
        {
            rb.InOrder();
        }

        Iterator begin()
        {
            return rb.Begin();
        }

        Iterator end()
        {
            return rb.End();
        }

        const_Iterator begin() const
        {
            return rb.Begin();
        }

        const_Iterator end() const
        {
            return rb.End();
        }

            

    private:
        rb_tree rb;

    public:
        static void Test1()
        {
            // const int &a = 1;  /*这是一个非const 引用引用常量的例子， 这里会报错是因为1是常量。 如果想要引用， 必须使用const*/

            map<int, int> mp;
            mp.insert({1, 1});
            mp.insert({13, 1});
            mp.insert({12, 1});

            mp.insert({16, 1});
            mp.insert({11, 1});
            mp.insert({14, 1});
            mp.insert({15, 1});

            mp.InOrder();
            cout << endl;

            map<int, int>::Iterator it = mp.begin();
            while (it != mp.end())
            {
                cout << it->first << ": " << it->second << endl;
                ++it;
            }
        }
        static void Test2()
        {
            string strs[] = {"苹果", "香蕉", "梨子", "栗子", "李子", "鸡蛋", "黄瓜", "苹果", "香蕉", "鸡蛋", "桃"};
            mian_yang::map<string, int> mp;
            for (auto e : strs)
            {
                mp[e]++;
            }

            // for (auto e : mp)
            // {
            //     cout << e.first << ":" << e.second << endl;
            // }
            for (auto [x, y] : mp)
            {
                cout << x << ":" << y << endl;
            }
        }
    };
}
